package com.hq.ims.data.service;

import com.hq.ims.data.dao.BusInfoTrackMapper;
import com.hq.ims.data.entity.*;
import com.hq.ims.data.utils.WebExpandUtils;
import com.hq.ims.data.vo.BusInfoFeedbackMapstruct;
import com.hq.ims.data.vo.BusInfoTrackMapstruct;
import com.hq.ims.data.vo.pic.BusiInfoTraceCompanyTreeVo;
import com.hq.ims.data.vo.pic.CompanyTreeVo;
import com.hq.mybatis.base.BaseService;
import com.hq.mybatis.base.page.RequestPage;
import com.hq.utils.util.ListUtils;
import com.hq.utils.util.ObjectUtils;
import com.hq.utils.util.ParentChildrenClassificationUtils;
import com.hq.utils.util.StringUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 蒋柏平
 * @detail 经营信息跟踪 服务实现类
 * @since 20241024
 */
@Service
public class BaseBusInfoTrackService extends BaseService<BusInfoTrackMapper, BusInfoTrack> {
    @Resource
    private BaseCompanyService baseCompanyService;
    @Resource
    private BusInfoTrackMapper busInfoTrackMapper;
    @Resource
    private BaseBusiIndustryCompanyService baseBusiIndustryCompanyService;
    @Resource
    private BaseBusInfoFeedbackService baseBusInfoFeedbackService;
    @Resource
    private BaseAreaService baseAreaService;

    /**
     * 经营信息跟踪-列表查询
     *
     * @param page     分页对象
     * @param searchVo 条件搜索对象
     */
    public void getByPage(RequestPage<BusInfoTrackMapstruct.BusInfoTrackVo> page,
                          BusInfoTrackMapstruct.PageSearchVo searchVo) {
        page = busInfoTrackMapper.pageList(page, searchVo);
        List<BusInfoTrackMapstruct.BusInfoTrackVo> busInfoTrackVoList = page.getRecords();
        busInfoTrackVoList.forEach(busInfoTrackVo -> {
            // 查询推送公司
            List<BusiIndustryCompany> industryCompanyList = baseBusiIndustryCompanyService.lambdaQuery()
                    .select(BusiIndustryCompany::getCompanyName)
                    .eq(BusiIndustryCompany::getBusiInfoId, busInfoTrackVo.getBusiInfoId())
                    .eq(BusiIndustryCompany::getIndustryId, busInfoTrackVo.getIndustryMarkId())
                    .list();
            String pushCompany = industryCompanyList.stream().map(BusiIndustryCompany::getCompanyName).distinct().collect(Collectors.joining(","));
            busInfoTrackVo.setPushCompany(pushCompany);
        });
        page.setRecords(busInfoTrackVoList);
    }

    /**
     * 经营信息跟踪-详情
     *
     * @param busInfoTrackId 主键id
     * @return BusInfoTrackMapstruct.DetailVo
     */
    public BusInfoTrackMapstruct.DetailVo getDetailVo(String busInfoTrackId) {
        BusInfoTrackMapstruct.DetailVo detailVo = busInfoTrackMapper.getDetailVo(busInfoTrackId);
        // 反馈详情列表
        List<BusInfoFeedback> busInfoFeedbackList = baseBusInfoFeedbackService.lambdaQuery()
                .eq(BusInfoFeedback::getBusInfoTrackId, busInfoTrackId)
                .orderByDesc(BusInfoFeedback::getFeedbackDate)
                .list();
        if (CollectionUtils.isNotEmpty(busInfoFeedbackList)) {
            List<BusInfoFeedbackMapstruct.FeedbackDetailVo> feedbackDetailVoList =
                    baseBusInfoFeedbackService.assembleFeedbackFileAndDeriveInfo(busInfoFeedbackList);
            detailVo.setFeedbackDetailVoList(feedbackDetailVoList);
        }
        return detailVo;
    }

    /**
     * 查询经营信息跟踪-公司查询
     *
     * @param isUserFlag  是否是用户端
     * @param companyName 公司名
     * @return ReturnVo
     */
    public BusiInfoTraceCompanyTreeVo getBusInfoTraceCountByCompany(Boolean isUserFlag, String companyName) {
        String companyId = WebExpandUtils.getHeadCompanyId();
        if (StringUtils.isNotEmpty(companyName)) {
            Company company = baseCompanyService.lambdaQuery()
                    .eq(Company::getCompanyName, companyName)
                    .eq(isUserFlag, Company::getRootId, WebExpandUtils.getHeadCompanyId())
                    .one();
            if (company == null) {
                return null;
            }
            companyId = company.getCompanyId();
        }
        Company company = baseCompanyService.getById(companyId);
        if (company == null) {
            return null;
        }
        //获取所有子公司
        List<Company> allChildrenCompanyList = baseCompanyService.getAllChildrenCompanyList(company.getCompanyId(), true);
        List<CompanyTreeVo> companyTreeVoList = new ArrayList<>();
        for (Company c : allChildrenCompanyList) {
            Long count = this.lambdaQuery().eq(BusInfoTrack::getCompanyId, c.getCompanyId()).count();
            CompanyTreeVo companyTreeVo = new CompanyTreeVo();
            companyTreeVo.setCompanyId(c.getCompanyId());
            companyTreeVo.setCompanyName(c.getCompanyName());
            companyTreeVo.setCompanyAddress(c.getCompanyAddress());
            companyTreeVo.setParentId(c.getParentId());
            companyTreeVo.setProjectCount(count);
            companyTreeVo.setProjectTotalCount(count);
            Area area = baseAreaService.lambdaQuery().eq(Area::getAreaId, c.getCity()).one();
            if (ObjectUtils.isNotNull(area)) {
                companyTreeVo.setCity(area.getAreaName());
            }
            companyTreeVo.setCompanyDivideIntoRuleValue(c.getCompanyDivideIntoRuleValue());
            List<BusiIndustryCompany> industryCompanyList = baseBusiIndustryCompanyService.lambdaQuery()
                    .eq(BusiIndustryCompany::getCompanyId, c.getCompanyId()).list();
            String industryName = industryCompanyList.stream().map(BusiIndustryCompany::getIndustryName)
                    .distinct().collect(Collectors.joining(","));
            companyTreeVo.setIndustryName(industryName);
            companyTreeVoList.add(companyTreeVo);
        }
        //转换为树
        companyTreeVoList = ParentChildrenClassificationUtils.classificationToTree(
                companyTreeVoList,
                CompanyTreeVo::getCompanyId,
                CompanyTreeVo::getParentId,
                CompanyTreeVo::setChildrenCompanyList,
                d -> d.setParentId(company.getRootId()),
                company.getParentId()
        );
        // 递归计算项目总数量
        recursionCount(companyTreeVoList);
        // 查询项目跟踪列表
        List<String> companyIdList = allChildrenCompanyList.stream().map(Company::getCompanyId).collect(Collectors.toList());
        List<BusInfoTrackMapstruct.BusInfoTrackVo> busInfoTrackVoList = busInfoTrackMapper.getBusInfoTrackListByCompanyId(companyIdList);
        BusiInfoTraceCompanyTreeVo busiInfoTraceCompanyTreeVo = new BusiInfoTraceCompanyTreeVo();
        busiInfoTraceCompanyTreeVo.setCompanyTreeVoList(companyTreeVoList);
        busiInfoTraceCompanyTreeVo.setProjectTrackList(busInfoTrackVoList);
        return busiInfoTraceCompanyTreeVo;
    }

    /**
     * 递归计算项目数量
     *
     * @param companyTreeVoList vo
     * @return long
     */
    public long recursionCount(List<CompanyTreeVo> companyTreeVoList) {
        long totalCount = 0L;
        if (ListUtils.isExistsEle(companyTreeVoList)) {
            for (CompanyTreeVo companyTreeVo : companyTreeVoList) {
                // 当前节点及子孙节点数量
                long currentTotalCount = companyTreeVo.getProjectCount() + recursionCount(companyTreeVo.getChildrenCompanyList());
                companyTreeVo.setProjectTotalCount(currentTotalCount);
                totalCount += currentTotalCount;
            }
        }
        return totalCount;
    }
}